const { app, BrowserWindow, ipcMain } = require('electron'), path = require('path');
const Baidu = require("./baidu");

let win = null;
//console.log(process.argv);

async function createWindow (){
	win = new BrowserWindow({
		width: 800,
		height: 600,
		autoHideMenuBar: true,
		webPreferences:{
			preload: path.join(__dirname, 'preload.js'),
			nodeIntegration: true
		}
	})
	//判断登录
	let baidu = new Baidu();
	if(await baidu.loginCheck()){
		if(process.argv[2] == 'dev'){
			//打开调试窗口
			win.webContents.openDevTools();
			win.loadURL('http://localhost:5173/');
		}else{
			//win.webContents.openDevTools();
			win.loadFile('ui/index.html');
		}
	}else{
		reload();
	}

	ipcMain.on("reload", ()=>{
		reload();
	});
	ipcMain.on("openPlayer", openPlayer);
}

/** 重新登录 */
function reload(){
	let baidu = new Baidu();
	if(process.argv[2] == 'dev'){
		//打开调试窗口
		win.webContents.openDevTools();
	}
	win.loadURL(baidu.loginUrl());
	win.webContents.on('did-navigate', loginSuccess);	
}

function openPlayer(evt, url){
	let win = new BrowserWindow({
		width: 1296,
		height: 759,
		autoHideMenuBar: true,
		webPreferences:{
			preload: path.join(__dirname, 'preload.js'),
			webSecurity: false,
			nodeIntegration: true,
		},
		//titleBarStyle: 'hidden',
	});
	if(process.argv[2] == 'dev'){
		win.webContents.openDevTools();
		win.loadURL('http://localhost:5173/player.html?' + url);
	}else{
		//win.webContents.openDevTools();
		win.loadFile('ui/player.html',{search:encodeURI(url)});
	}	
}

/** 登录成功 */
async function loginSuccess(e, url){
	//console.log("loginSuccess", e, url);
	let baidu = new Baidu();
	//if(await baidu.loginSuccess(e.sender.getURL())){
	if(await baidu.loginSuccess(url)){
		//win.webContents.off('did-finish-load', loginSuccess);
		win.webContents.off('did-navigate', loginSuccess);
		if(await baidu.loginCheck()){
			if(process.argv[2] == 'dev'){
				win.webContents.openDevTools();
				win.loadURL('http://localhost:5173/');
			}else{
				win.loadFile('ui/index.html');
			}
		}
	}
}

app.whenReady().then(()=>{
	createWindow()
})